import pymysql as MySQLdb  # 这里是python3  如果你是python2.x的话，import MySQLdb
import os

host = os.getenv('MYSQL_HOST')
user = os.getenv('MYSQL_USERNAME')
passwd = os.getenv('MYSQL_PASSWORD')
port = os.getenv('MYSQL_PORT')
db = os.getenv('MYSQL_DATABASE')


class SelectMySQL(object):
    def select_data(self, sql):
        print("====================")
        print(type(port))
        result = []
        try:
            conn = MySQLdb.connect(host=host, port=int(port), user=user, passwd=passwd, db=db, charset='utf8')
            cur = conn.cursor()
            cur.execute(sql)
            alldata = cur.fetchall()
            # print(alldata)
            for rec in alldata:
                result.append(rec[0])  # 注意，我这里只是把查询出来的第一列数据保存到结果中了,如果是多列的话，稍微修改下就ok了
        except Exception as e:
            print(e)
        finally:
            conn = MySQLdb.connect(host=host, port=int(port), user=user, passwd=passwd, db=db, charset='utf8')
            cur = conn.cursor()
            cur.execute(sql)
            cur.close()
            conn.close()

        return result

    def get_result(self, sql, filename):
        results = self.select_data(sql)
        print('The amount of datas: %d' % (len(results)))
        print(results)
        with open(filename, 'w') as f:
            for result in results:
                f.write(str(result) + '\n')
        print('Data write is over!')
        return results
